<template>
  <div v-if="logined">
    <el-page-header
      icon="el-icon-arrow-left"
      content="用户信息"
      @click="goTo(route.query.redirect)"
    ></el-page-header>
    <el-row :gutter="20">
      <el-col :md="2"></el-col>
      <el-col :md="20" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>用户信息</span>
            </div>
          </template>
          <el-descriptions :column="2">
            <el-descriptions-item>
              <template #label><i class="el-icon-user"></i> 用户名 </template
              >{{ userInfo.nickname }}</el-descriptions-item
            >
            <el-descriptions-item>
              <template #label> <i class="el-icon-phone"></i> 手机号 </template
              >{{ userInfo.phone }}</el-descriptions-item
            >
            <el-descriptions-item>
              <template #label> <i class="el-icon-message"></i> 邮箱 </template>
              {{
                userInfo.email ? userInfo.email : "(空)"
              }}</el-descriptions-item
            >
            <el-descriptions-item>
              <template #label>
                <i class="el-icon-money"></i> 账户余额 </template
              >￥{{ userInfo.amount }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <i class="el-icon-alarm-clock"></i> 注册时间 </template
              >{{ createTime }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :md="2"></el-col>
      <el-col :md="20" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单信息</span>
            </div>
          </template>
          <el-table
            :size="'mini'"
            :data="OrderList"
            :max-height="winHeight"
            :summary-method="sumOrderAmount"
            v-loading="loading && OrderList.length === 0"
            style="width: 100%"
            id="OrderTable"
            stripe
            border
            show-summary
          >
            <el-table-column type="index" width="50" />
            <el-table-column prop="createTime" label="创建时间" sortable />
            <el-table-column prop="orderNo" label="订单号" sortable />
            <el-table-column prop="orderAmount" label="订单金额" sortable />
            <el-table-column prop="orderSource" label="支付方式" sortable />
            <el-table-column prop="orderInfo" label="订单信息" sortable />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :md="2"></el-col>
      <el-col :md="20" :xs="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>消费记录</span>
            </div>
          </template>
          <el-table
            :size="'mini'"
            :data="ConsumptionList"
            :max-height="winHeight"
            :summary-method="sumConsumptionAmount"
            v-loading="loading2 && ConsumptionList.length === 0"
            style="width: 100%"
            id="ConsumptionTable"
            show-summary
            stripe
            border
          >
            <el-table-column type="index" width="50" />
            <el-table-column prop="Time" label="日期" sortable />
            <el-table-column prop="Message" label="类别" sortable />
            <el-table-column prop="Amount" label="单价" sortable />
            <el-table-column prop="Num" label="数量" sortable />
            <el-table-column prop="Sum" label="金额" sortable />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { useRoute } from "vue-router";
import { useStore } from "vuex";
import { computed, toRefs, ref, reactive, onMounted } from "vue";
import { ApiGetUserOrders, ApiGetUserConsumptions } from "@/http/api";
import { ElMessage } from "element-plus";
import { formatTime } from "@/libs/utils";
import { goTo } from "@/libs/utils";

export default {
  setup() {
    const store = useStore();
    const route = useRoute();
    const loading = ref(true);
    const loading2 = ref(true);
    const OrderList = reactive([]);
    const ConsumptionList = reactive([]);
    const winHeight = ref(parseInt(window.innerHeight * 0.5));
    onMounted(() => {
      fetchOrderList();
      fetchConsumptionList();
    });
    const logined = computed(() => {
      return store.state.token && store.state.userInfo;
    });
    //求订单合计
    const sumOrderAmount = (param) => {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        } else if (index === 3) {
          const values = data.map((item) => Number(item[column.property]));
          if (values.length < 1) return;
          const sum = values.reduce((acr, cur) => {
            return acr + cur;
          });
          sums[index] = `￥${sum.toFixed(2)}`;
        } else {
          sums[index] = "N/A";
        }
      });
      return sums;
    };
    //求消费合计
    const sumConsumptionAmount = (param) => {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        } else if (index === 4 || index === 5) {
          const values = data.map((item) => Number(item[column.property]));
          if (values.length < 1) return;
          const sum = values.reduce((acr, cur) => {
            return acr + cur;
          });
          sums[index] = index === 4 ? `${sum}份` : `￥${sum.toFixed(2)}`;
        } else {
          sums[index] = "N/A";
        }
      });
      return sums;
    };
    //获取消费记录
    const fetchConsumptionList = () => {
      ApiGetUserConsumptions().then((res) => {
        if (res.code === 2000) {
          for (let key in res.data) {
            let arr = key.split("==");
            let record = reactive({
              Time: arr[0],
              Message: arr[1],
              Amount: arr[2],
              Num: res.data[key],
              Sum: (parseFloat(arr[2]) * parseInt(res.data[key])).toFixed(2),
            });
            ConsumptionList.push(record);
          }
        } else {
          ElMessage.error(`获取消费记录失败:${res.message}`);
        }
      });
    };
    //获取用户订单记录
    const fetchOrderList = () => {
      ApiGetUserOrders().then((res) => {
        if (res.code === 2000) {
          for (let i in res.data) {
            let row_data = res.data[i];
            let orderData = reactive({
              createTime: formatTime(new Date(row_data.create_time)),
              orderNo: row_data.order_no,
              orderAmount: row_data.amount,
              orderSource: row_data.source,
              orderInfo: row_data.order_name,
            });
            OrderList.push(orderData);
          }
        } else {
          ElMessage.error(`获取订单信息失败:${res.message}`);
        }
        loading.value = false;
      });
    };
    const createTime = computed(() => {
      let date = new Date(store.state.userInfo.create_time);
      return formatTime(date);
    });
    return {
      createTime,
      loading,
      loading2,
      OrderList,
      ConsumptionList,
      winHeight,
      logined,
      ...toRefs(store.state),
      sumOrderAmount,
      sumConsumptionAmount,
      goTo,
      route,
    };
  },
};
</script>

<style>
</style>